//
//  HSSlideMenuViewController.swift
//  HSSlideMenuView
//
//  Created by haisheng huang on 16/3/9.
//  Copyright © 2016年 haisheng huang. All rights reserved.
//

import UIKit

let screenWidth = UIScreen.mainScreen().bounds.size.width //屏幕的宽度
let screenHeight = UIScreen.mainScreen().bounds.size.height //屏幕的高度
let deckCanNotPanViewTag = 987654   // 不响应此侧滑的View的tag

/*样式*/
public enum HSSlideMenuDirection {
    case left
    case right
}


class HSSlideMenuViewController: UIViewController, UIGestureRecognizerDelegate {

    var mainPageDistance: CGFloat = 100.0 //打开左侧窗时，中视图(右视图)露出的宽度
    var mainPageScale: CGFloat = 0.7 //打开左侧窗时，中视图缩放比例

    var vSlideSpeed: CGFloat = 0.9 //滑动速度 0.5～1.0
    
    var leftAlpha: CGFloat = 0.9 //左侧蒙版的最大值
    var leftCenterX: CGFloat = 30.0 //左侧初始偏移量
    var leftScale: CGFloat = 0.7 //左侧初始缩放比例
    
    var leftViewController: UIViewController? //左侧窗控制器
    var mainViewController: UIViewController? //主窗控制器
    var rightViewController: UIViewController? //右窗控制器
    var sideslipTap: UITapGestureRecognizer? //点击手势控制器，是否允许点击视图恢复视图位置。默认为yes
    var pan: UIPanGestureRecognizer? //滑动手势控制器
    var closed: Bool? //侧滑窗是否关闭(关闭时显示为主页)
    var scaleX: CGFloat? = 0.0//实时横向位移
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: 打开左侧窗时，中视图中心点
    func getMainPageCenter(direction: HSSlideMenuDirection) -> CGPoint {
        
        if direction == HSSlideMenuDirection.left {
            return CGPointMake(screenWidth + screenWidth * mainPageScale / 2.0 -  mainPageDistance, screenHeight / 2.0)
        } else if direction == HSSlideMenuDirection.right {
            return CGPointMake(-screenWidth / 2.0 + mainPageDistance, screenHeight / 2.0)
        } else {
            return CGPointMake(screenWidth / 2.0, screenHeight / 2.0)
        }
        
    }
    
    // MARK: 滑动距离大于此数时，状态改变（关--》开，或者开--》关）
    func getCouldChangeDeckStateDistance() -> CGFloat {
        return (screenWidth - mainPageDistance) / 2.0 - 40.0
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        
    }
    
    func initViewController(mainView: UIViewController?, leftView: UIViewController?, rightView: UIViewController) -> Void {
        
        self.leftViewController = leftView
        self.mainViewController = mainView
        self.rightViewController = rightView
        
        //滑动手势
        self.pan = UIPanGestureRecognizer.init(target: self, action: "panEventHandle:")
        self.mainViewController?.view.addGestureRecognizer(self.pan!)
        self.pan?.cancelsTouchesInView = true
        self.pan?.delegate = self
        
        self.leftViewController?.view.hidden = true
        self.view.addSubview((self.leftViewController?.view)!)
        self.rightViewController!.view.hidden = true
        self.view.addSubview((self.rightViewController?.view)!)
        self.view.addSubview((self.mainViewController?.view)!)
        self.closed = true //初始时侧滑窗关闭
        
    }
    
    class func initViewController(mainView: UIViewController?, leftView: UIViewController?, rightView: UIViewController) -> HSSlideMenuViewController {
        
        let view = HSSlideMenuViewController()
        
        view.initViewController(mainView, leftView: leftView, rightView: rightView)
        
        return view
        
    }
    
    // MARK: 滑动手势
    func panEventHandle(sender: UIPanGestureRecognizer) -> Void {
        
        let point: CGPoint = sender.translationInView(self.view)
        scaleX = CGFloat(point.x) * vSlideSpeed + scaleX!
        
        var needMoveWithTap: Bool = true //是否还需要跟手指移动
        
        if self.mainViewController?.view.frame.origin.x <= 0.0 && scaleX <= 0.0 || self.mainViewController?.view.frame.origin.x >= (screenWidth - mainPageDistance) && scaleX >= 0 {
            //边界值管控
            scaleX = 0.0
            needMoveWithTap = false
        }
        
        // 根据视图位置判断是左滑还是右边滑动
        if needMoveWithTap && sender.view?.frame.origin.x >= 0.0 && sender.view?.frame.origin.x <= (screenWidth - mainPageDistance) {
            
            var senderCenterX = (sender.view?.center.x)! + point.x * vSlideSpeed
            
            if senderCenterX < (screenWidth * 0.5 - 2) {
                senderCenterX = screenWidth * 0.5
            }
            
            let senderCenterY = sender.view?.center.y
            
            sender.view?.center = CGPointMake(senderCenterX, senderCenterY!)

            //scale 1.0 ~ mainPageScale
            let scale = 1 - (1 - mainPageScale) * ((sender.view?.frame.origin.x)! / (screenWidth - mainPageDistance))
            
            sender.view?.transform = CGAffineTransformScale(CGAffineTransformIdentity, scale, scale)
            sender.setTranslation(CGPointMake(0, 0), inView: self.view)
            
//            let leftTabCenterX = leftCenterX + ((screenWidth - mainPageDistance) * 0.5 - leftCenterX) * ((sender.view?.frame.origin.x)! / (screenWidth - mainPageDistance))
//            //leftScale kLeftScale~1.0
//            let tempLeftScale = leftScale + (1 - leftScale) * ((sender.view?.frame.origin.x)! / (screenWidth - mainPageDistance))
            
            
        } else {
            
            //超出范围
            if self.mainViewController?.view.frame.origin.x < 0 {
                
                self.closeLeftView()
                self.scaleX = 0.0
                
            } else if (self.mainViewController?.view.frame.origin.x > (screenWidth - mainPageDistance)) {
                
                self.openLeftView()
                self.scaleX = 0.0
            }
        }
        
        //手势结束后修正位置,超过约一半时向多出的一半偏移
        
        if sender.state == UIGestureRecognizerState.Ended {
        
            if fabs(self.scaleX!) > getCouldChangeDeckStateDistance() {
                
                if self.closed == true {
                    self.openLeftView()
                } else {
                    self.closeLeftView()
                }
                
            } else {
                
                if self.closed == true {
                    self.closeLeftView()
                } else {
                    self.openLeftView()
                }
            }
            
            self.scaleX = 0
        }
        
    }
    
    // MARK: 单击手势
    
    func tapEventHandle(sender: UITapGestureRecognizer) -> Void {
    
        if self.closed == false && sender.state == UIGestureRecognizerState.Ended {
        
            UIView.beginAnimations(nil, context: nil)
            sender.view?.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)
            sender.view?.center = CGPointMake(screenWidth / 2.0, screenHeight / 2.0)
            self.closed = true
            UIView.commitAnimations()
            
            self.scaleX = 0.0
            self.removeSingleTap()
        }
    }
    
    /**
     * 关闭左视图
     *
     **/
    
    func closeLeftView() -> Void {
    
        UIView.beginAnimations(nil, context: nil)
        self.mainViewController?.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)
        self.mainViewController?.view.center = CGPointMake(screenWidth / 2.0, screenHeight / 2.0)
        self.closed = true
        UIView.commitAnimations()
        self.removeSingleTap()
        
    }
    
    /**
     * 打开左视图
     *
     **/
    
    func openLeftView() -> Void {
    
        self.leftViewController!.view.hidden = false
        self.rightViewController?.view.hidden = true
        
        UIView.beginAnimations(nil, context: nil)
        self.mainViewController?.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, mainPageScale, mainPageScale)
        self.mainViewController?.view.center = self.getMainPageCenter(HSSlideMenuDirection.left)
        self.closed = false
        UIView.commitAnimations()
        
        self.disableTapButton()
    }
    
    /**
     * 关闭右视图
     *
     **/
     
    func closeRightView() -> Void {
        
        UIView.beginAnimations(nil, context: nil)
        self.mainViewController?.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)
        self.mainViewController?.view.center = CGPointMake(screenWidth / 2.0, screenHeight / 2.0)
        self.closed = true
        UIView.commitAnimations()
        self.removeSingleTap()
    }
    
    /**
     * 打开右视图
     **/
     
    func openRightView() -> Void {
    
        self.leftViewController!.view.hidden = true
        self.rightViewController?.view.hidden = false
        
        UIView.beginAnimations(nil, context: nil)
        self.mainViewController?.view.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)
        self.mainViewController?.view.center = self.getMainPageCenter(HSSlideMenuDirection.right)
        self.closed = false
        UIView.commitAnimations()
        
        self.disableTapButton()
    }
     
    /**
     * 关闭行为收敛
     **/
    
    func removeSingleTap() -> Void {
        
        for tempButton in (self.mainViewController?.view.subviews)! {
            
            if tempButton is UIButton {
                tempButton.userInteractionEnabled = true
            }
        }
        
        if self.sideslipTap != nil {
            self.mainViewController?.view.removeGestureRecognizer(self.sideslipTap!)
            self.sideslipTap = nil
        }
    }
    
    /**
     * 行为收敛控制
     **/
     
    func disableTapButton() -> Void {
        
        for tempButton in (self.mainViewController?.view.subviews)! {
            
            if tempButton is UIButton {
                tempButton.userInteractionEnabled = false
            }
        }
        
        //单击
        if self.sideslipTap != nil {
            
            self.sideslipTap = UITapGestureRecognizer.init(target: self, action: "tapEventHandle")
            self.sideslipTap?.numberOfTapsRequired = 1
            self.mainViewController?.view.addGestureRecognizer(self.sideslipTap!)
            self.sideslipTap?.cancelsTouchesInView = true //点击事件盖住其它响应事件,但盖不住Button
        }
        
    }
    
    /**
     * 设置滑动开关是否开启
     * @param enabled YES:支持滑动手势，NO:不支持滑动手势
     **/
    
    func setPanEnabled(enabled: Bool) -> Void {
    
        self.pan?.enabled = enabled
    }
    
    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
        
        if touch.view?.tag == deckCanNotPanViewTag {
            return false
        } else {
            return true
        }
    }
    
}
